#!/usr/bin/env python

# (c) 2007-2011 Helsinki University of Technology and University of Helsinki
# Licensed under the MIT license; see LICENSE.txt for more information.

try:			# rdflib 2.4.x
  from rdflib.Graph import Graph, URIRef
except ImportError:	# rdflib 3.0.0
  from rdflib import Graph, URIRef

import cPickle
import os.path
import sys
import os
import os.path

def debug(debug, msg):
  if debug:
    print >>sys.stderr, msg

def rdf_parse(model, fname, formats):
  for format in formats:
    try:
      model.parse(fname, format=format)
      return True
    except:
      pass
  return False


def loadrdf(fname, backend='pickle', formats=['xml'], dbg=True):
  if backend == 'pickle':
    picklename = fname + ".pickle"
    if os.path.exists(picklename) and os.stat(picklename).st_mtime > os.stat(fname).st_mtime:
      debug(dbg, "Loading pickled version '%s' of RDF file '%s'..." % (picklename, fname))
      m = cPickle.load(file(picklename))
      debug(dbg, "Done.")
      return m
    else:
      debug(dbg,"Please wait: loading and pickling RDF file '%s'." % fname)
      m = Graph()
      debug(dbg, "Loading...")
      if not rdf_parse(m, fname, formats):
        debug(dbg, "Parsing failed.")
        return None
      debug(dbg, "Pickling to '%s'..." % picklename)
      cPickle.dump(m, file(picklename, 'w'), cPickle.HIGHEST_PROTOCOL)
      debug(dbg, "Done.")
      return m
  elif backend == 'sleepycat':
    dbpath = fname + '.db'
    if os.path.exists(dbpath) and max([os.stat(dbpath + "/" + fn).st_mtime for fn in os.listdir(dbpath)]) > os.stat(fname).st_mtime:
      debug(dbg, "Opening Sleepycat database '%s' of RDF file '%s'..." % (dbpath, fname))
      m = Graph('Sleepycat', URIRef(fname))
      m.open(dbpath)
      return m
    else:
      debug(dbg, "Please wait: loading RDF file '%s' to Sleepycat database" % fname)
      m = Graph('Sleepycat', URIRef(fname))
      m.open(dbpath, True)
      debug(dbg, "Loading...")
      if not rdf_parse(m, fname, formats):
        debug(dbg, "Parsing failed.")
        return None
      debug(dbg, "Done.")
      return m
      
  else:
    raise ValueError('Unknown backend: ' + backend)
